<template>
	<div class="lm-dialogue-panel">
		<div class="dialogue-panel-inner">
			<!--识别模块(识别情绪、标签、意图)-->
			<lm-recognition-module v-if="!isPreview"></lm-recognition-module>
			<!--主内容-->
			<lm-chatgpt-body :isPreview="isPreview"></lm-chatgpt-body>
			<!--底部操作-->
			<lm-chatgpt-footer :isPreview="isPreview"></lm-chatgpt-footer>
		</div>
	</div>
</template>

<script>
import LmRecognitionModule from './lm-dialogue-panel/lm-recognition-module'
import LmChatgptBody from './lm-dialogue-panel/lm-chatgpt-body'
import LmChatgptFooter from './lm-dialogue-panel/lm-chatgpt-footer'
import { mapState, mapMutations } from "vuex"
export default {
	name: 'LmDialoguePanel',
	props: {
		isPreview: {
			type: Boolean,
			default: false
		}
	},
	components: {
		LmRecognitionModule,
		LmChatgptBody,
		LmChatgptFooter
	},
	data() {
		return {
			llmSocket: null,
			llmHeartCheck: {
				timeout: 25000, // 25秒发一次心跳
				timeoutObj: null
			},
			reconnectAttempts: 0, // 重连尝试次数
			maxReconnectAttempts: 5, // 最大重连尝试次数
			reconnectInterval: 1000, // 初始重连间隔时间，单位毫秒
			needReconnect: true, // 是否需要重连
		}
	},
	mounted() {
		this.needReconnect = true
		this.createLlmSocket()
	},
	beforeDestroy() {
		this.needReconnect = false
		if(this.llmSocket) {
			this.llmSocket.close()
		}
	},
	methods: {
		...mapMutations('lm-chat', ['pushGptMessageList']),
		// 创建websocket
		createLlmSocket () {
			if (typeof WebSocket === 'undefined') {
				console.log('您的浏览器不支持WebSocket')
			} else {
				console.log('您的浏览器支持WebSocket')
				console.log(this.llmSocket)
				if (this.llmSocket !== null) {
					this.llmSocket.close()
					this.llmSocket = null
					clearTimeout(this.llmHeartCheck.timeoutObj)
				}
				this.llmSocket = new WebSocket(LOCAL_CONFIG.LLMWs)
				// 打开事件
				this.llmSocket.onopen = () => {
					console.log('大模型websocket已打开')
					this.startHeartCheck() // 心跳检测重置
					console.log('大模型websocket连接成功!' + new Date().toLocaleString())
				}
				// 获得消息事件
				this.llmSocket.onmessage = msg => {
					this.startHeartCheck() // 如果获取到消息，心跳检测重置
					let msgData = JSON.parse(msg.data)
					if (msgData.data) {
						let data = msgData.data
						let item = {
							clientId: data.clientId,
							message_type:  data.msgSide || '4', // message_type 1.用户->代理人 2.代理人->用户 3.代理人->大模型 4.大模型->代理人
							message_body_type: data.aiccMsgType,
							create_time: data.createTime || '',
							message: data.aiccMsgContent,
							msgId: data.msgId
						}
						this.pushGptMessageList(item)
					}
				}
				// 关闭事件
				this.llmSocket.onclose = () => {
					console.log('大模型websocket已关闭' + new Date().toLocaleString())
					this.needReconnect && this.reconnectWebSocket() // 添加重连逻辑
				}
				// 发生了错误事件
				this.llmSocket.onerror = function () {
					console.log('大模型websocket发生了错误' + new Date().toLocaleString())
				}
			}
		},
		startHeartCheck (type) {
			clearTimeout(this.llmHeartCheck.timeoutObj)
			this.llmHeartCheck.timeoutObj = setTimeout(() => {
				// 这里发送一个心跳，后端收到后，返回一个心跳消息，
				// onmessage拿到返回的心跳就说明连接正常
				this.llmSocket.send('2')
			}, this.llmHeartCheck.timeout)
		},
		 // 重新连接
		 reconnectWebSocket() {
			if (this.reconnectAttempts < this.maxReconnectAttempts) {
				console.log(`大模型websocket尝试重新连接，当前尝试次数：${this.reconnectAttempts}`);
				setTimeout(() => {
					this.createLlmSocket(); // 尝试重新创建WebSocket连接
					this.reconnectAttempts++; // 重连次数加一
					// 可以考虑增加重连间隔递增逻辑，例如：this.reconnectInterval *= 2;
				}, this.reconnectInterval);
			} else {
				console.error('大模型websocket达到最大重连次数，不再尝试重连');
				this.reconnectAttempts = 0; // 重置重连次数，以便下次连接时重新计算
				this.llmSocket = null; // 确保状态正确
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.lm-dialogue-panel{
	width: 100%;
	height: 100%;
	position: relative;
	background-size: 100% 100%;
	border-right: 1px solid rgba(231,231,231,1);
	background-image: linear-gradient(177deg, rgba(227,239,255,0.71) 0%, #FFFFFF 32%);
	.dialogue-panel-inner{
		background-image: url(../../assets/images/lm-bg.png);
		background-size: 510px 144px;
		background-repeat: no-repeat;
		background-position: center 0px;
		padding: 20px 0;
		display: flex;
		flex-direction: column;
		height: 100%;
	}
}
</style>